<?php
/**
 * @Author: laoweizhen <1149243551@qq.com>,
 * @Date: 2022/10/07 10:01,
 * @LastEditTime: 2022/10/07 10:01
 */
declare(strict_types=1);

namespace Zhen\HyperfKit;


use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Request;

class CoreRequest extends Request
{
    #[Inject]
    protected CoreResponse $response;

    public function addStoredParsedData(string $key, $value)
    {
        Context::set($this->contextkeys['parsedData'], array_merge(
            Context::get($this->contextkeys['parsedData']),
            [$key => $value]
        ));
    }

    /**
     * 获取请求IP.
     */
    public function ip(): string
    {
        $ip = $this->getServerParams()['remote_addr'] ?? '0.0.0.0';
        $headers = $this->getHeaders();

        if (isset($headers['x-forwarded-for'])) { // 优先从 x-forwarded-for 中获取ip地址
            $ip = explode(',', $headers['x-forwarded-for'][0])[0];
        } elseif (isset($headers['x-real-ip'])) {
            $ip = $headers['x-real-ip'][0];
        } elseif (isset($headers['http_x_forwarded_for'])) {
            $ip = $headers['http_x_forwarded_for'][0];
        }

        return $ip;
    }

    /**
     * 获取协议架构.
     */
    public function getScheme(): string
    {
        if (isset($this->getHeader('X-scheme')[0])) {
            return $this->getHeader('X-scheme')[0] . '://';
        }
        return 'http://';
    }
}